/**
 * Copyright(C) com.allinpay - 通联支付 上海研发中心
 * 
 * @author 王斌
 *
 * @since 2013年9月25日
 * @description: <描述>
 * 
 */

var thour = new Array();
var addresses = new Array();
var dinnerDate = "";

$(document).ready(function() {
	$('#hours').change(function(){ 
		var v=$(this).children('option:selected').val();//这就是selected的值 
		buildTimeMinsOption(v,"mins");
	}) ;
	
	$("#address_reserved").click(function() {
		var nextGo = $(this).next();
		nextGo.animate({
			height : 'toggle',
			opacity : 'toggle',
			duration : "slow"
		}, function(){
			if ($(this).css('display') == 'none'){
				$("#address_reserved").removeClass('xl-infor-f-up');
				$("#address_reserved").addClass('xl-infor-f02');
			}else{
				$("#address_reserved").removeClass('xl-infor-f02');
				$("#address_reserved").addClass('xl-infor-f-up');
			}
		});
		return false;
	});
	
	$("#t_numberOfTableware").change(function () {
		var num = $(this).val();
		if (num > 100 || isNaN(num)) {
			var span = $("#num_invalid"); //$(this).parent().next("div");
			span.html('<font style=\"color:red;\"> 输入不合法</font>');
			$(this).val($("#numberOfTableware").val());
			setTimeout("$('#num_invalid').html('')", 2000);
		}
	});
	
	$("#takeoutfrom").submit(function(e){
		var target = "apis/restaurant/takeOut";
		var ajax_data = {
			"rid" : r_id,
			"numberOfTableware":$("#numberOfTableware").val(),
			"dinnerTime" : getDinnerTimeForSubmit(),
			"address_id" : $("#address_id").val(),
			"contactPerson" : $("#contactPerson").val(),
			"contactPhone" : $("#contactPhone").val(),
			"contactAddress": $("#contactAddress").val(), 
			"access_token":access_token
		};
		
		if (!checkSubmitInfo(ajax_data)) {
			e.preventDefault();
		}else{
			if (ajax_data.address_id == "" || ajax_data.address_id == null) {
				ajax_data.address_id = -1;
			}
			ajax_post_json(target, ajax_data, function() {
				setInfoMsg("正在提交信息，请稍候...", false);
				$("#nextButton").attr("disabled","true");
			}, function(data) {
				if (data.result == true) {
					setTimeout("goMenu('" + $("#next_t").val() + "')", 10);
				} else if (data.result == false && data.type == "msg") {
					setInfoMsg(data.content, true);
					$("#nextButton").removeAttr("disabled");
				}
			}, function(xhr, textStatus, errorThrown) {
				setInfoMsg("系统繁忙，请稍后再试 ", true);
				ef_alert("takeout submit: " + xhr.statusText);
				$("#nextButton").removeAttr("disabled");
			});
			return false;
		}
	});
	
	request_customer_address("addresses_reserved");

	var todayStr = date2String(new Date());
	request_dinner_time(todayStr);  //"2013-10-30 09:41:12"
});

function date2String(date){     // 2014-01-03 09:50:00  (js 0 ~ 11  一月~ 十二月) 
	var todayArr = date.toArray();
	
	var todayStr = todayArr[0];                   //year  4
	todayStr = todayStr + "-";
	todayStr += format2digit(todayArr[1]+1); // month 2     
	todayStr = todayStr + "-";
	todayStr += format2digit(todayArr[2]);    // day 2
	
	todayStr = todayStr + " ";
	todayStr += format2digit(todayArr[3]);    // hour 2
	todayStr = todayStr + ":";
	todayStr += format2digit(todayArr[4]);    // min 2
	todayStr = todayStr + ":";
	todayStr += format2digit(todayArr[5]);    // sec 2
	
	//ef_alert("takeout date2string: " + todayStr);
	return todayStr;
}

function checkSubmitInfo(data) {
	
	if (!isValidDate(data.dinnerTime)) {
		setInfoMsg("今天已过外卖时段，请明天早点预定，谢谢", true);
		return false;
	} else if (data.contactAddress.trim() == "" || data.contactAddress.length < 2) {
		setInfoMsg("请确保选择的联系方式含有效地址", true);
		return false;
	} else if (data.contactPhone.trim() == "") {
		setInfoMsg("您选择的联系方式中的手机号码有误", true);
		return false;
	} else if (!isValidPhoneNumber(data.contactPhone)) {
		setInfoMsg("手机号码格式不对", true);
		return false;
	}
	
	return true;
}

function goMenu(url){
	window.location.href = url;
	return false;
}

function adjust_numOfMeals(op){
	var num = $("#t_numberOfTableware").val();
	if (op == 'increase'){
		if (num >=100 ) return;
		$("#t_numberOfTableware").val(++num);
	}else if (op == 'reduce'){
		if (num == 1)	return;
		$("#t_numberOfTableware").val(--num);
	}else{
		return;
	}
	$("#numberOfTableware").val(num);
}

function getDinnerTimeForSubmit(){
	var hour = $("#hours").children('option:selected').val();
	var min = $("#mins").children('option:selected').val();
	
	if (parseInt(hour) == -1 || parseInt(min) == -1) {
		return "";
	}
	
	// 2013-10-29 21:30:00
	var todayArr = (new Date()).toArray();
	var timeStr = todayArr[0];                     //year  4
	timeStr = timeStr + "-";
	timeStr += format2digit(todayArr[1]+1);   // month 2
	timeStr = timeStr + "-";
	timeStr += format2digit(todayArr[2]);      // day 2
	
	timeStr = timeStr + " ";
	timeStr += format2digit(parseInt(hour));   // hour 2
	timeStr = timeStr + ":";
	timeStr += format2digit(parseInt(min));    // min 2
	timeStr = timeStr + ":";
	timeStr += format2digit(0);                    // sec 2

	//ef_alert("getDinnerTimeForSubmit: " + timeStr);
	return timeStr;
}

function beforeSend(){
};
function m_error(xhr, textStatus, errorThrown){
}

function request_dinner_time(t_date) {
	ajax_post_json("apis/restaurant/dinnerTime", {
		"rid" : r_id,
		"dinnerDate" : t_date, 
		"access_token":access_token
	}, beforeSend, function(data) {
		if (data.result == true){
			initDinnerTime(data.content);
		}else{
			setTimeout(buildTimeHoursOption('hours'),10);
		}
	}, m_error);
}

function newDinnerTime(hour, mins){
	var dt = new Object();
	dt.hour = hour;
	dt.mins = mins;
	return dt;
}

function initDinnerTime(data){
	thour.length = 0;
	$.each(data, function(index, item) {
		var minArr = new Array();
		$.each(item.mins, function(index1, item1) {
			minArr[index1] = item1;
		});
		thour[index] = newDinnerTime(item.hour, minArr);
	});
	setTimeout(buildTimeHoursOption('hours'),10);
}

function buildTimeHoursOption(elementId){
	var optionHtml = "";
	var fisrt = -1;
	$.each(thour, function(index, item) {
		if (index == 0) fisrt = item.hour;
		optionHtml += "<option value=\"" + item.hour + "\">" + item.hour + "</option>";
	});
	
	if (optionHtml == "") {
		optionHtml = "<option value=\"" + -1 + "\">" + "小时" + "</option>";
	}
	$("#" + elementId).empty();
	$("#" + elementId).append(optionHtml);
	buildTimeMinsOption(fisrt, "mins");
}

function buildTimeMinsOption(hour,elementId){
	var mins = [];
	$.each(thour, function(index, item) {
		if (item.hour == hour) mins = item.mins;
	});

	var optionHtml = "";
	if (hour == -1) {
		optionHtml = "<option value=\"" + -1 + "\">" + "分钟" + "</option>";
	}else {
		$.each(mins, function(index, item) {
			if (item < 10){
				optionHtml += "<option value=\"0" + item + "\">0" + item + "</option>";
			}else{

				optionHtml += "<option value=\"" + item + "\">" + item + "</option>";
			}
		});
	}
	$("#" + elementId).empty();
	$("#" + elementId).append(optionHtml);
}

function choose_reserved_address(id, contact, phone, address){
	$("#address_id").val(id);
	$("#contactPerson").val(contact);
	$("#contactPhone").val(phone);
	$("#contactAddress").val(address);
}

function choose_address(id, contact, phone, address){
	choose_reserved_address(id, contact, phone, address);
	
	var input = $("#address_list").find("input:radio");
	 input.each(function(){
		 if (this.id == id){
			 this.checked = true;
		 }
	 });
}

function newAddress(id, contact, phone, address){
	var addr = new Object();
	addr.id = id;
	addr.contact = contact;
	addr.phone = phone;
	addr.address=address;
	return addr;
}
/*
<div id=\"address_list\" style=\"padding-left: 0px; border-spacing:5px;\">"
	<div class=\"center-f\">" 
		<input type=\"radio\">" 
		<a href="">
			<span style="color:#333;">name</span>
			<span style="color:#333;">tel</span>
			<span style="color:#333; padding-left:16px;">address</span>
		</a>
	</div>
</div>
*/
function request_customer_address(elementId){
	ajax_post_json("apis/user/address", {
		"user_id" : u_id,
		"option" : "RETRIEVE_ALL", 
		"access_token":access_token
	}, beforeSend, function(data) {
		var pHtml = "";
		var count = 0;
		pHtml += "<div id=\"address_list\" style=\"padding-left: 0px; border-spacing:5px;\">";
		$.each(data.content, function(index, item) {
			if (data.content.length == 1 || count == data.content.length-1)
				pHtml += "<div class=\"bottom-f\">";
			else
				pHtml += "<div class=\"center-f\">";
			pHtml += "<input type=\"radio\" id=\""+item.id+"\" name=\"addr_radio\" value=\"" + item.id + "\"> ";
			pHtml += "<a href=\"javascript:choose_address('"+item.id+"','"+item.contactPerson+"','"+item.contactTel+"','"+(item.addressArea+" "+ item.contactAddress)+"')\"";
			pHtml += "<span style=\"color:#333;\">" +item.contactPerson+"</span>";
			pHtml += "<span style=\"color:#333; padding-left:18px;\">" +item.contactTel+"</span><br/>";
			pHtml += "<span style=\"color:#333; padding-left:18px;\">" +item.addressArea +" " + item.contactAddress+"</span>";
			pHtml += "</a></div>";
			
			addresses[index] = newAddress(item.id, item.contactPerson, item.contactTel, item.addressArea+" "+ item.contactAddress);
			count ++;
		});
		pHtml += "</div>";
		
		$("#" + elementId).empty();
		$("#" + elementId).append(pHtml);
		
		 var input = $("#address_list").find("input:radio");
		 input.each(function(){
			 if (this.id == $("#address_id").val()){
				 this.checked = true;
			 }
		 });
			
		$("input[type=radio][name=addr_radio]").click(function() {
			var cur_addr_id = this.id;
			$.each(addresses, function(index, item){
				if (item.id == cur_addr_id){
					choose_reserved_address(item.id, item.contact, item.phone, item.address);
					return false;
				}
			});
		});
	}, m_error);
}

function prompt_info_animate() {
	$("#prompt_info_c").animate({
		height : 'toggle',
		opacity : 'toggle',
		duration : "slow"
	}, function(){
		if ($("#prompt_info").hasClass("prompt_info_down")) {
			$("#prompt_info").removeClass("prompt_info_down");
			$("#prompt_info").addClass("prompt_info_up");
		}else{
			$("#prompt_info").removeClass("prompt_info_up");
			$("#prompt_info").addClass("prompt_info_down");
		}
	});
}

function setInfoMsg(msg, disappear){
	
	if (isValide(msg) && msg.length > 0) {
		$("#info_msg").html(msg);
		$("#info_msg_div").css({"display":"block", "height":"0px"});
		$("#info_msg_div").animate({
			height : '24px',
			duration : "slow"
		}, function(){});
	}else {
		$("#info_msg_div").animate({
			height : '0px',
			duration : 'slow'
		}, function(){
			$("#info_msg_div").css({"display":"none", "height":"0px"});
			$("#info_msg").html(msg);
		});
	}
	
	if (disappear){
		setTimeout("setInfoMsg('', false)", 5000);
	}
}
